#pragma once
#define DATA_PATH "contacts.bin"
#include <iostream>
#include <fstream>
#include"ContactException.hpp"
/*
    持久化方式,将数据存储到文件中
*/
#include "Contacts.pb.h"

class ContactMapper
{
private:
public:
    ContactMapper()
    {}
    ~ContactMapper()
    {}
    //读取一个通讯录
    void SelectContact(contacts::Contacts *contacts) const
    {
        std::fstream input(DATA_PATH, std::ios::in | std::ios::binary);
        if (!input)
        {
            std::cout << "---> (ContactsMapper::selectContacts) " << DATA_PATH << ":File not found.Creating a new file." << std::endl;
        }
        if(!contacts->ParseFromIstream(&input)){
            input.close();
            throw ContactException("SelectContact: failed to parse Contacts");
        }
        input.close();
    }
    //插入一个通讯录
    void InsertContact(contacts::Contacts &contacts) const
    {
        std::fstream output(DATA_PATH,std::ios::out|std::ios::binary);
        //将通讯录序列化，并输入文件
        if(!contacts.SerializePartialToOstream(&output)){
            output.close();
            throw ContactException("(ContactsMapper::insertContacts) Failed towrite contacts.");
        }
        output.close();
    }
};
